﻿using System;
using System.Data;
using System.Windows.Forms;
using Util.Database;

namespace ConfigureNZBLoader.EditControls
{
    public partial class Settings : EditControls.BaseEditControl
    {
        public Settings()
        {
            InitializeComponent();

            txtNZBFolder.Text = "";
            try
            {
                using (IDbCommand cmd = DB.CreateCommand())
                {
                    cmd.CommandText = "select value from property where name = 'NZB Download Folder'";
                    txtNZBFolder.Text = cmd.ExecuteScalar().ToString();

                    cmd.CommandText = "select value from property where name = 'DB Version'";
                    lblDBVersion.Text = string.Format(System.Globalization.CultureInfo.InvariantCulture, "DB Version: {0}", cmd.ExecuteScalar());
                }
            }
            catch (System.Data.Common.DbException) { }
        }

        private void btnUpdate_Click(object sender, EventArgs e)
        {
            using (IDbCommand cmd = DB.CreateCommand())
            {
                cmd.CommandText = "delete from property where name = 'NZB Download Folder'";
                cmd.ExecuteNonQuery();

                string Folder = txtNZBFolder.Text;
                if(!Folder.EndsWith("\\", StringComparison.OrdinalIgnoreCase))
                {
                    Folder += "\\";
                }

                cmd.CommandText = "insert into property(name, value) values('NZB Download Folder', ?)";
                IDataParameter par = cmd.CreateParameter();
                par.Value = Folder;
                cmd.Parameters.Add(par);
                cmd.ExecuteNonQuery();

                txtNZBFolder.Text = Folder;
            }
        }

        private void btnBrowse_Click(object sender, EventArgs e)
        {
            if(fbd.ShowDialog(this.Parent) == DialogResult.OK)
            {
                txtNZBFolder.Text = fbd.SelectedPath;
            }
        }
    }
}
